<template>
  <div class="shortcut-settings space-y-6">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-foreground mb-2 flex items-center">
        <i class="i-mdi-keyboard-variant mr-3 w-6 h-6" />
        {{ t('settings.shortcuts.title') }}
      </h1>
      <p class="text-muted-foreground">{{ t('settings.shortcuts.description') }}</p>
    </div>

    <!-- 全局快捷键 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-earth mr-2 w-5 h-5" />
        {{ t('settings.shortcuts.global') }}
      </h2>

      <div class="space-y-4">
        <div
          v-for="shortcut in globalShortcuts"
          :key="shortcut.id"
          class="flex items-center justify-between p-3 border border-border rounded-lg hover:bg-muted/50 transition-colors">
          <div class="flex items-center">
            <i :class="[shortcut.icon, 'w-5 h-5 mr-3 text-primary']" />
            <div>
              <div class="font-medium text-foreground">{{ t(shortcut.nameKey) }}</div>
              <div class="text-sm text-muted-foreground">{{ t(shortcut.descriptionKey) }}</div>
            </div>
          </div>
          <div class="flex items-center space-x-2">
            <div class="flex items-center space-x-1">
              <kbd
                v-for="key in shortcut.keys"
                :key="key"
                class="px-2 py-1 text-xs bg-muted border border-border rounded">
                {{ key }}
              </kbd>
            </div>
            <button
              class="px-3 py-1 text-sm bg-secondary text-secondary-foreground rounded hover:bg-secondary/90 transition-colors"
              @click="editShortcut(shortcut)">
              {{ t('settings.shortcuts.editShortcut') }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 应用内快捷键 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-application mr-2 w-5 h-5" />
        {{ t('settings.shortcuts.app') }}
      </h2>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div v-for="category in appShortcuts" :key="category.nameKey" class="border border-border rounded-lg p-4">
          <h3 class="font-medium text-foreground mb-3 flex items-center">
            <i :class="[category.icon, 'w-4 h-4 mr-2']" />
            {{ t(category.nameKey) }}
          </h3>
          <div class="space-y-2">
            <div
              v-for="shortcut in category.shortcuts"
              :key="shortcut.id"
              class="flex items-center justify-between text-sm">
              <span class="text-muted-foreground">{{ t(shortcut.nameKey) }}</span>
              <div class="flex items-center space-x-1">
                <kbd
                  v-for="key in shortcut.keys"
                  :key="key"
                  class="px-1.5 py-0.5 text-xs bg-muted border border-border rounded">
                  {{ key }}
                </kbd>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷键设置 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-cog mr-2 w-5 h-5" />
        {{ t('settings.shortcuts.settings') }}
      </h2>

      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.shortcuts.enableGlobal') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.shortcuts.enableGlobalDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <input v-model="settings.enableGlobalShortcuts" type="checkbox" class="sr-only peer" />
            <div
              class="w-11 h-6 bg-muted peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
          </label>
        </div>

        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.shortcuts.showHints') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.shortcuts.showHintsDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <input v-model="settings.showShortcutHints" type="checkbox" class="sr-only peer" />
            <div
              class="w-11 h-6 bg-muted peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
          </label>
        </div>

        <div class="flex items-center justify-between">
          <div>
            <label class="text-sm font-medium text-foreground">{{ t('settings.shortcuts.conflictDetection') }}</label>
            <p class="text-xs text-muted-foreground">{{ t('settings.shortcuts.conflictDetectionDescription') }}</p>
          </div>
          <label class="relative inline-flex items-center cursor-pointer">
            <input v-model="settings.conflictDetection" type="checkbox" class="sr-only peer" />
            <div
              class="w-11 h-6 bg-muted peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
          </label>
        </div>
      </div>
    </div>

    <!-- 自定义快捷键 -->
    <div class="bg-card rounded-lg p-6 border border-border">
      <h2 class="text-lg font-semibold text-foreground mb-4 flex items-center">
        <i class="i-mdi-plus-circle mr-2 w-5 h-5" />
        {{ t('settings.shortcuts.custom') }}
      </h2>

      <div class="space-y-4">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label class="block text-sm font-medium text-foreground mb-2">{{
              t('settings.shortcuts.actionName')
            }}</label>
            <input
              v-model="newShortcut.name"
              type="text"
              class="w-full px-3 py-2 border border-input rounded-lg bg-input-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              :placeholder="t('settings.shortcuts.actionNamePlaceholder')" />
          </div>

          <div>
            <label class="block text-sm font-medium text-foreground mb-2">{{ t('settings.shortcuts.shortcut') }}</label>
            <input
              v-model="newShortcut.shortcut"
              type="text"
              readonly
              class="w-full px-3 py-2 border border-input rounded-lg bg-input-background text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent cursor-pointer"
              :placeholder="t('settings.shortcuts.shortcutPlaceholder')"
              @keydown="captureShortcut" />
          </div>

          <div>
            <label class="block text-sm font-medium text-foreground mb-2">{{ t('settings.shortcuts.command') }}</label>
            <select
              v-model="newShortcut.command"
              class="w-full px-3 py-2 border border-input rounded-lg bg-input-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
              <option value="">{{ t('settings.shortcuts.commandPlaceholder') }}</option>
              <option value="new-chat">{{ t('settings.shortcuts.commands.newChat') }}</option>
              <option value="toggle-sidebar">{{ t('settings.shortcuts.commands.toggleSidebar') }}</option>
              <option value="search">{{ t('settings.shortcuts.commands.search') }}</option>
              <option value="settings">{{ t('settings.shortcuts.commands.settings') }}</option>
            </select>
          </div>
        </div>

        <div class="flex gap-2">
          <button
            :disabled="!canAddShortcut"
            class="px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            @click="addCustomShortcut">
            {{ t('settings.shortcuts.addShortcut') }}
          </button>
          <button
            class="px-4 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/90 transition-colors"
            @click="clearNewShortcut">
            {{ t('common.clear') }}
          </button>
        </div>

        <!-- 自定义快捷键列表 -->
        <div v-if="customShortcuts.length > 0" class="mt-6">
          <h3 class="text-sm font-medium text-foreground mb-3">{{ t('settings.shortcuts.customShortcuts') }}</h3>
          <div class="space-y-2">
            <div
              v-for="(shortcut, index) in customShortcuts"
              :key="index"
              class="flex items-center justify-between p-3 border border-border rounded-lg">
              <div class="flex items-center">
                <div>
                  <div class="font-medium text-foreground">{{ shortcut.name }}</div>
                  <div class="text-sm text-muted-foreground">{{ shortcut.command }}</div>
                </div>
              </div>
              <div class="flex items-center space-x-2">
                <kbd class="px-2 py-1 text-xs bg-muted border border-border rounded">
                  {{ shortcut.shortcut }}
                </kbd>
                <button
                  class="px-2 py-1 text-sm bg-error text-error-foreground rounded hover:bg-error/90 transition-colors"
                  @click="removeCustomShortcut(index)">
                  {{ t('settings.shortcuts.deleteShortcut') }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="flex gap-3 pt-4">
      <button
        class="px-6 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors"
        @click="saveSettings">
        {{ t('common.save') }}
      </button>
      <button
        class="px-6 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/90 transition-colors"
        @click="resetSettings">
        {{ t('common.reset') }}
      </button>
      <button
        class="px-6 py-2 bg-secondary text-secondary-foreground rounded-lg hover:bg-secondary/90 transition-colors"
        @click="exportShortcuts">
        {{ t('common.export') }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';

import { t } from '@/i18n';

// 全局快捷键
const globalShortcuts = ref([
  {
    id: 'show-hide',
    nameKey: 'settings.shortcuts.actions.showHide',
    descriptionKey: 'settings.shortcuts.actions.showHideDescription',
    icon: 'i-mdi-window-maximize',
    keys: ['Ctrl', 'Shift', 'A']
  },
  {
    id: 'new-chat',
    nameKey: 'settings.shortcuts.actions.newChat',
    descriptionKey: 'settings.shortcuts.actions.newChatDescription',
    icon: 'i-mdi-chat-plus',
    keys: ['Ctrl', 'N']
  },
  {
    id: 'quick-search',
    nameKey: 'settings.shortcuts.actions.search',
    descriptionKey: 'settings.shortcuts.actions.searchDescription',
    icon: 'i-mdi-magnify',
    keys: ['Ctrl', 'K']
  }
]);

// 应用内快捷键分类
const appShortcuts = ref([
  {
    nameKey: 'settings.shortcuts.categories.navigation',
    icon: 'i-mdi-navigation',
    shortcuts: [
      { id: 'home', nameKey: 'nav.home', keys: ['Ctrl', '1'] },
      { id: 'chat', nameKey: 'nav.chat', keys: ['Ctrl', '2'] },
      { id: 'settings', nameKey: 'nav.settings', keys: ['Ctrl', ','] },
      { id: 'help', nameKey: 'common.help', keys: ['F1'] }
    ]
  },
  {
    nameKey: 'settings.shortcuts.categories.editing',
    icon: 'i-mdi-pencil',
    shortcuts: [
      { id: 'copy', nameKey: 'common.copy', keys: ['Ctrl', 'C'] },
      { id: 'paste', nameKey: 'common.paste', keys: ['Ctrl', 'V'] },
      { id: 'undo', nameKey: 'common.undo', keys: ['Ctrl', 'Z'] },
      { id: 'redo', nameKey: 'common.redo', keys: ['Ctrl', 'Y'] }
    ]
  },
  {
    nameKey: 'settings.shortcuts.categories.chat',
    icon: 'i-mdi-chat',
    shortcuts: [
      { id: 'send', nameKey: 'chat.send', keys: ['Enter'] },
      { id: 'new-line', nameKey: 'chat.newLine', keys: ['Shift', 'Enter'] },
      { id: 'clear', nameKey: 'chat.clear', keys: ['Ctrl', 'L'] },
      { id: 'history', nameKey: 'chat.history', keys: ['Ctrl', 'H'] }
    ]
  },
  {
    nameKey: 'settings.shortcuts.categories.view',
    icon: 'i-mdi-window-restore',
    shortcuts: [
      { id: 'minimize', nameKey: 'window.minimize', keys: ['Ctrl', 'M'] },
      { id: 'fullscreen', nameKey: 'window.fullscreen', keys: ['F11'] },
      { id: 'close', nameKey: 'window.close', keys: ['Ctrl', 'W'] },
      { id: 'quit', nameKey: 'window.quit', keys: ['Ctrl', 'Q'] }
    ]
  }
]);

// 设置数据
const settings = ref({
  enableGlobalShortcuts: true,
  showShortcutHints: true,
  conflictDetection: true
});

// 新快捷键
const newShortcut = ref({
  name: '',
  shortcut: '',
  command: ''
});

// 自定义快捷键列表
const customShortcuts = ref<Array<{ name: string; shortcut: string; command: string }>>([]);

// 是否可以添加快捷键
const canAddShortcut = computed(() => {
  return newShortcut.value.name && newShortcut.value.shortcut && newShortcut.value.command;
});

// 编辑快捷键
const editShortcut = (shortcut: any) => {
  console.log('编辑快捷键:', shortcut);
  // 这里可以打开编辑对话框
};

// 捕获快捷键
const captureShortcut = (event: KeyboardEvent) => {
  event.preventDefault();

  const keys: string[] = [];
  if (event.ctrlKey) keys.push('Ctrl');
  if (event.shiftKey) keys.push('Shift');
  if (event.altKey) keys.push('Alt');
  if (event.metaKey) keys.push('Meta');

  if (event.key && !['Control', 'Shift', 'Alt', 'Meta'].includes(event.key)) {
    keys.push(event.key.toUpperCase());
  }

  newShortcut.value.shortcut = keys.join(' + ');
};

// 添加自定义快捷键
const addCustomShortcut = () => {
  if (canAddShortcut.value) {
    customShortcuts.value.push({ ...newShortcut.value });
    clearNewShortcut();
  }
};

// 清空新快捷键
const clearNewShortcut = () => {
  newShortcut.value = {
    name: '',
    shortcut: '',
    command: ''
  };
};

// 删除自定义快捷键
const removeCustomShortcut = (index: number) => {
  customShortcuts.value.splice(index, 1);
};

// 保存设置
const saveSettings = () => {
  console.log('保存快捷键设置:', {
    settings: settings.value,
    customShortcuts: customShortcuts.value
  });
  alert(t('settings.model.saveSuccess'));
};

// 重置设置
const resetSettings = () => {
  if (confirm(t('settings.appearance.resetConfirm'))) {
    settings.value = {
      enableGlobalShortcuts: true,
      showShortcutHints: true,
      conflictDetection: true
    };
    customShortcuts.value = [];
    console.log('快捷键设置已重置');
  }
};

// 导出快捷键配置
const exportShortcuts = () => {
  const config = {
    settings: settings.value,
    customShortcuts: customShortcuts.value
  };

  const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'shortcuts-config.json';
  a.click();
  URL.revokeObjectURL(url);
};
</script>

<style scoped>
.shortcut-settings {
  max-width: 1000px;
}

kbd {
  font-family: ui-monospace, SFMono-Regular, 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;
}
</style>
